package com.example.common.util;

import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.ServiceLoader;

/**
 * @Author Peng Yisheng
 * @Date 2024/11/27 0:42
 * @Description 服务工具类
 */
@Slf4j
public class ServiceUtil {

    /**
     * spi加载一个实现类
     * @param serviceClass
     * @return
     * @param <T>
     */
    public static <T> T loadService(Class<T> serviceClass) {
        ServiceLoader<T> serviceLoader = ServiceLoader.load(serviceClass);
        Iterator<T> iterator = serviceLoader.iterator();
        if (iterator.hasNext()) {
            return iterator.next();
        } else {
            log.error("not found implementation for " + serviceClass.getName());
            throw new RuntimeException("not found implementation for " + serviceClass.getName());
        }
    }

}
